<?php

function encode_license($domains = array(), $expire, $comment = '')
{
	global $private_key;
	
	$license = implode(',', $domains).'#'.$expire.'#'.$comment;

	$key = encode_string($license);
	return $key;
}

function decode_license($key)
{
	$license = explode('#', decode_string($key), 3);
	$license[0] = explode(',', $license[0]);
	return $license;
}


function encode_string($str)
{
	$p=11;
	$g=2;
	$x = 7;//rand(2, $p-1);

	$message = bin2hex($str);	
	$message = str_split($message, 4);
	
	$code = '';
	$shift = $x;
	foreach($message as $block)
	{	
		$y = pow($g, $x)%$p;
		$block = base_convert($block, 16, 10);
		$enc_block = '';
		for($i=0;$i<strlen($block);$i++)
		{
			$k = rand(2, $p-1);			
			$a = pow($g, $k)%$p+($i+$shift)%26;
			$b = ((pow($y%$p, $k)%$p)*(intval($block[$i])))%$p+($i+$shift)%25;
			
			$enc_block .= base_convert($a, 10, 36);
			$enc_block .= base_convert($b, 10, 36);
		}
		$code .= $enc_block.' ';
		$shift+=$x;
	}
	return $code;
}

function decode_string($code)
{
	$p=11; $g=2; $x=7;
	$code = trim($code);

	$blocks = explode(' ', $code);
	$res = '';
	$s = $x;
	foreach($blocks as $block)
	{
		$m = '';
		for($i=0; $i<strlen($block); $i+=2)
		{
			$a = base_convert($block[$i], 36, 10)-($i/2+$s)%26;
			$b = base_convert($block[$i+1], 36, 10)-($i/2+$s)%25;
			$m .= ($b * (pow($a,$p-$x-1) )) % $p;
		}
		$m = base_convert($m, 10, 16);
		for ($a=0; $a<strlen($m); $a+=2)
			$res .=chr(hexdec($m{$a}.$m{($a+1)}));
		$s+=$x;
	}
	return  $res;
}
